<?php

session_start();

$video_id = $_GET['video_id'];
$tagInput = $_GET['tagInput'];

include('../../../sidebardbinfo-live.php');

// connect to the database
$addtagslink = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$addtagslink) {
	die('Problem connecting to database server : ' . mysql_error());
}

// make $dbname the current db
$addtagsdb_selected = mysql_select_db($dbname, $addtagslink);
if (!$addtagsdb_selected) {
	die ('Problem connecting to database : ' . mysql_error());
}

// check to see if the tag exists in the list of existing keywords
$checkwordstmt = "SELECT word_id FROM tags_keywords WHERE word='".addslashes($tagInput)."'";
$checkwordres = mysql_query($checkwordstmt);
if (!$checkwordres) {
	die ('Problem with query : ' . mysql_error());
}

$addThisWordToLookup = false;

// word not in existing keyword list
if (mysql_num_rows($checkwordres)==0) {
	$insertwordstmt = "INSERT INTO tags_keywords (word) VALUES ('".addslashes($tagInput)."')";
	$insertwordres = mysql_query($insertwordstmt);
	if (!$insertwordres) {
		die ('Problem with query : ' . mysql_error());
	}
	// retrieve the word_id from the word just added
	$getwordidstmt = "SELECT word_id FROM tags_keywords WHERE word = '".addslashes($tagInput)."'";
	$getwordidres = mysql_query($getwordidstmt);
	if (!$getwordidres) {
		die ('Problem with query : ' . mysql_error());
	}
	$word_id = mysql_result($getwordidres,0);
	$addThisWordToLookup = true;
} else {
	// word does exist in keyword list, now check if exists for current video
	$word_id = mysql_result($checkwordres,0);
	$videotagstmt = "SELECT word_id FROM tags_lookup WHERE video_id = '".$video_id."' AND word_id = ".$word_id;
	$videotagres = mysql_query($videotagstmt);
	if (!$videotagres) {
		die ('Problem with query : ' . mysql_error());
	}
	// keyword not associated with video so add to lookup table
	if (mysql_num_rows($videotagres)==0) $addThisWordToLookup = true;
}

if ($addThisWordToLookup) {
	$insertlookupstmt = "INSERT INTO tags_lookup (video_id,word_id) VALUES ('".$video_id."','".$word_id."')";
	$insertlookupres = mysql_query($insertlookupstmt);
	if (!$insertlookupres) {
		die ('Problem with query : ' . mysql_error());
	}
	echo "<p>tag '".$tagInput."' added</p>";
} else {
	echo "<p>tag '".$tagInput."' already exists!</p>";
}

mysql_close($addtagslink);

?>